<template>
	<view>
		<!-- #ifdef H5 -->
		<back></back>
		<!-- #endif -->
		<view class="out">
			<view class="card" @click="jump('/yCreate/pages/mineAddress?id='+JSON.stringify(ids))">
				<view class="top u-flex-center u-row-between">
					<view>收货地址</view>
					<text style="font-size: 28rpx;">选择收货地址</text>
				</view>
				<view class="u-p-t-30 u-flex-center u-row-between">
					<view class="address u-flex-center">
						<image src="@/static/yCreate/addressIcon.png" mode="widthFix"></image>
						<view class="message" v-if="addressDetail">
							<view class="name u-flex">{{addressDetail.name}} <text
									class="u-m-l-30">{{addressDetail.mobile}}</text></view>
							<div style="margin-top: 15rpx;">
								{{addressDetail.province}} {{addressDetail.city}} {{addressDetail.district}} {{addressDetail.address}}
							</div>
						</view>
						<view v-else>
							请选择收货地址
						</view>
					</view>
					<image src="@/static/yCreate/right2.png" mode="widthFix" class="right-icon"></image>
				</view>
			</view>
			<view class="card" v-for="(item,index) in orderData.lists"
				@click.stop="$func.jump('/pages/index/findDetail?id='+item.id)">
				<view class="u-flex-center u-row-between">
					<view class="shop-message u-flex">
						<image src="@/static/yCreate/shopIcon.png" mode="widthFix"></image>
						<view>{{item.shop_name}}</view>
						<view class="standing standing2 u-flex-center" v-if="item.shop.isself==1">平台</view>
						<view class="standing u-flex-center" v-else>商家</view>
					</view>
					<image src="@/static/yCreate/right.png" mode="widthFix" class="right-icon"></image>
				</view>
				<view class="card-item u-flex-center" v-for="(_item,_index) in item.products">
					<view class="u-flex u-col-top" style="width: 100%;">
						<image :src="_item.image" mode="aspectFill" class="goods-img"></image>
						<view class="message u-flex-col" style="width: 100%;">
							<view class="u-line-2">{{_item.title}}</view>
							<view class="cate">规格：<text
									v-for="(__item,__index) in _item.sku.difference">{{__item+' '}}</text></view>
							<view class="u-flex u-row-between u-m-t-20">
								<view class="price"><text>￥</text>{{_item.sku.price}}</view>
								<view class="number">×{{_item.number}}</view>
							</view>
						</view>
					</view>
				</view>
				<view>
					<view class="item-message u-flex-center u-row-between">
						<text>快递运费</text>
						<view class="u-flex">{{item.freight.name}}
							<view style="font-size: 18rpx;">￥</view>{{item.freight.price}}
						</view>
					</view>
					<view class="item-message u-flex-center u-row-between" @click="showCoupon(item,index)">
						<text>优惠折扣</text>
						<view class="u-flex-center" v-if="item.coupon.type=='discount'">
							{{item.coupon.discount?item.coupon.discount+'折':'请选择'}}
							<image src="@/static/yCreate/right.png" mode="widthFix"></image>
						</view>
						<view class="u-flex-center" v-if="item.coupon.type=='reduction'">
							{{item.coupon.limit?'满'+Number(item.coupon.limit)+'减'+Number(item.coupon.price):'请选择'}}
							<image src="@/static/yCreate/right.png" mode="widthFix"></image>
						</view>
						<view class="u-flex-center" v-if="!item.coupon.type">
							请选择
							<image src="@/static/yCreate/right.png" mode="widthFix"></image>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="placeholder"></view><!-- 防止内容塌陷 -->
		<view class="btn-box">
			<view class="u-flex u-row-between" style="width: 100%;">
				<view class="u-flex">
					<view class="total">合计：</view>
					<view class="price" v-if="orderData.statis"><text>￥</text>{{totalPrice}}</view>
				</view>
				<view class="btn u-flex-center" @click="submit">确认支付</view>
			</view>
		</view>
		<u-popup v-model="show" mode="bottom" border-radius="25" height="60%" closeable safe-area-inset-bottom>
			<view class="coupon">
				<view class="cou_tit">优惠券</view>
				<view style="height: 100rpx;"></view>
				<view v-for="(item,index) in couponList" :key="index" class="cou_item">
					<!-- <view class="cou_grey" v-if="item.state"></view> -->
					<view class="left">
						<view class="u-flex u-col-top" style="height: 100%;padding-left: 20rpx;" v-if="item.type=='discount'">
							<view class="cou_price">{{item.discount}}</view>
							<view style="height: 100%;padding-top: 20rpx;">
								<view class="title">{{item.name}}</view>
								<view class="tips u-flex-center">满{{item.limit}}打{{item.discount}}折</view>
								<view class="time u-flex u-row-right">到期时间：{{item.enddate}}</view>
							</view>
						</view>
						<view class="u-flex u-col-top" style="height: 100%;padding-left: 20rpx;" v-if="item.type=='reduction'">
							<view class="cou_price">{{item.price}}</view>
							<view style="height: 100%;padding-top: 20rpx;">
								<view class="title">{{item.name}}</view>
								<view class="tips u-flex-center">满{{item.limit}}减{{item.price}}</view>
								<view class="time u-flex u-row-right">到期时间：{{item.enddate}}</view>
							</view>
						</view>
						
					</view>
					<view class="status u-flex-center" @tap="$u.throttle(ling(item), 1700)">
						{{!item.state ? '立即领取' : '立即使用'}}
					</view>
				</view>
				<view style="height: 10rpx;"></view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	//#ifdef  H5
	var wx = require('jweixin-module')
	//#endif
	export default {
		data() {
			return {
				couponList: [],
				show: false,
				list: [],
				addressDetail: {},
				orderData: {},
				ids: [],
				isNull: false,
				token: '',
				subList: [],
				showIndex: 0,
				showItem: {},
				ok:true
			};
		},
		watch: {
			isNull(newValue, oldVlaue) {
				if (newValue) {
					if(this.ok){
						this.getDetail()
					}
				}
			}
		},
		computed: {
			totalPrice() {
				let price = Number(this.orderData.statis.allsub)
				let zheprice = ''
				this.orderData.lists.map(item => {
					if (item.coupon.type=='discount') {
						zheprice = item.order_price-((item.order_price*Number(item.coupon.discount))*0.1)
						price = (price-zheprice).toFixed(2)
					}else if(item.coupon.type=="reduction"){
						price = price - Number(item.coupon.price)
						price = price.toFixed(2)
					}
				})
				return price
			}
		},
		onShow() {
			this.getDetail()
		},
		onLoad(options) {
			this.ids = JSON.parse(options.ids)
			if (options.subList) {
				this.subList = JSON.parse(options.subList)
			}

		},
		methods: {
			ling(item) {
				if (!item.state) {
					this.$u.post('/api/wanlshop/coupon/receive', {
						id: item.id,
					}).then(res => {
						if (res.code == 1) {
							this.$u.toast(res.data.msg)
							this.couponShow = false
							this.showCoupon(this.showItem, this.showIndex)
						} else {
							this.$u.toast(res.msg)
							this.couponShow = false
						}
					});
				} else {
					this.orderData.lists[this.showIndex].coupon = item;
					this.orderData.lists[this.showIndex].coupon_id = item.id;
					this.show = false
				}
			},
			showCoupon(item, index) {
				let goods_id = []
				let shop_category_id = []
				item.products.map(item2 => {
					goods_id.push(item2.id)
					shop_category_id.push(item2.shop_category_id)
				})
				this.$u.post('/api/wanlshop/coupon/query', {
					goods_id: goods_id.join(','),
					price: item.order_price,
					shop_category_id: shop_category_id.join(','),
					shop_id: item.shop.id,
				}).then(res => {
					this.couponList = res.data
					this.show = true
					this.showIndex = index
					this.showItem = item
				})
			},
			submit() {
				if (!this.ok) return
				console.log('+++++++++++++++');
				let that = this
				this.subList.map(item => {
					item.checked = true
				})
				this.orderData.lists.map((item, index) => {
					// item.coupon_id=0
					item.products.map(item2 => {
						item2.goods_id = item2.id
						item2.sku_id = item2.sku.id
						item2.freight_id = item2.freight.id
					})
				})
				console.log(this.orderData.lists,'-+========================');
				this.$u.post('/api/wanlshop/order/addOrder', {
					order: {
						address_id: this.addressDetail.id,
						lists: this.orderData.lists
					},
					token: this.token
				}).then(res => {
					console.log(res,'999999999999999999');
					if (res.code == 1) {
						let method = ''
						method = 'app'
						let order_id = []
						res.data.list.map(item => {
							order_id.push(item.order_id)
						})
						this.$u.post('/api/wanlshop/pay/payment', {
							code: null,
							method: 'app',
							order_id: order_id,
							order_type: 'goods',
							type: 'wechat'
						}).then(res2 => {
							console.log(res2,'AAAAAAAAAAAAAA');
							if (res2.code == 1) {
								// #ifdef H5
								wx.config({
									debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
									appId: res2.data.appId, // 必填，公众号的唯一标识
									timestamp: res2.data.timeStamp, // 必填，生成签名的时间戳
									nonceStr: res2.data.nonceStr, // 必填，生成签名的随机串
									signature: res2.data.paySign, // 必填，签名
									jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表
								})
								// #endif
								console.log(JSON.parse(res2.data).appid,'appidappidappidappidappidappid');
								let orderInfo = JSON.parse(res2.data);
								// #ifdef H5
								wx.ready(function() {
								// #endif
								//获取支付渠道
								var wxpaySev = null;
								plus.payment.getChannels(function(channels){
									for (var i in channels) {
										var channel = channels[i];
										if (channel.id === 'wxpay') {
											wxpaySev = channel;
										}
									}
									//发起支付
									plus.payment.request(wxpaySev, orderInfo, function(result) {
										var rawdata = JSON.parse(result.rawdata);
											uni.showToast({
												title: '支付成功'
											})
											that.$u.post(
											'/api/wanlshop/cart/storage', {
												data: that.subList,
												type: 'del'
											})
											setTimeout(() => {
												uni.redirectTo({
													url: '/yCreate/pages/goodsOrder'
												})
											}, 1500)
										}, function(e) {
											console.log("支付失败：" + JSON.stringify(e));
											uni.showToast({
												title: '支付失败',
												icon: 'none'
											})
											that.$u.post(
											'/api/wanlshop/cart/storage', {
												data: that.subList,
												type: 'del'
											})
											setTimeout(() => {
												uni.redirectTo({
													url: '/yCreate/pages/goodsOrder'
												})
											}, 1500)
										});
									}, function(e){
										console.log("获取支付渠道失败：" + JSON.stringify(e));
										uni.showToast({
											title: '支付失败',
											icon: 'none'
										})
									});
								return
									uni.requestPayment({
										timeStamp:orderInfo.timestamp, // 时间戳
										nonceStr:orderInfo.noncestr, // 随机数
										packageValue:orderInfo.package, //
										sign:orderInfo.sign,
										appId:orderInfo.appid,
										partnerId:orderInfo.partnerid,
										prepayId:orderInfo.prepayid,
										provider: 'wxpay',
										success: function() {
											uni.showToast({
												title: '支付成功'
											})
											that.$u.post(
											'/api/wanlshop/cart/storage', {
												data: that.subList,
												type: 'del'
											})
											setTimeout(() => {
												uni.reLaunch({
													url: '/yCreate/pages/goodsOrder'
												})
											}, 1500)
										},
										cancel: function() {
											uni.showToast({
												title: '取消支付',
												icon: 'none'
											})
											that.$u.post(
											'/api/wanlshop/cart/storage', {
												data: that.subList,
												type: 'del'
											})
											setTimeout(() => {
												uni.reLaunch({
													url: '/yCreate/pages/goodsOrder'
												})
											}, 1500)
										},
										fail: function( err ) {
											console.log(err,'支付失败');
											uni.showToast({
												title: '支付失败',
												icon: 'none'
											})
											that.$u.post(
											'/api/wanlshop/cart/storage', {
												data: that.subList,
												type: 'del'
											})
											setTimeout(() => {
												uni.reLaunch({
													url: '/yCreate/pages/goodsOrder'
												})
											}, 1500)
										}
									})
								// #ifdef H5
								})
								// #endif
								// this.$u.toast(res.msg)
								// this.$u.post('/api/wanlshop/cart/storage',{
								// 	data:this.subList,
								// 	type:'del'
								// })
								// setTimeout(()=>{
								// 	// this.jump('/yCreate/pages/goodsOrder')
								// 	uni.reLaunch({
								// 		url:'/yCreate/pages/goodsOrder'
								// 	})
								// },1500)
							} else {
								this.$u.toast(res2.msg)
							}
						}).catch(err => {
							console.log(err, '支付失败');
						})
					} else {
						this.$u.toast(res.msg)
					}
				}).catch(err2 => {
					console.log(err2, '--------------------');
				})
			},
			getDetail() {
				this.$u.post('/api/wanlshop/order/getOrderGoodsList', {
					data: this.ids,
					address_id: this.addressDetail.id,
				}).then(res => {
					if (res.code == 1) {
						this.addressDetail = res.data.addressData
						this.orderData = res.data.orderData
						this.orderData.lists.map((item, index) => {
							item.coupon_id = 0
							item.coupon = {}
						})
						this.token = res.data.token
						this.ok = true;
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 1000
						});
						this.ok = false;
						setTimeout(() => {
							this.jump('/yCreate/pages/mineAddress?id=' + JSON.stringify(this.ids) + '&isNull=' + true)
						}, 1500)
					} 
				})
			},
			jump(url) {
				uni.navigateTo({
					url: url
				})
			},
			call() {
				const phoneNumbers = ['10086', '10010', '10000'];

				// 循环拨打电话
				phoneNumbers.forEach((phoneNumber) => {
					uni.makePhoneCall({
						phoneNumber: phoneNumber, // 电话号码
						success: function() {
							console.log('Call Success');
						},
						fail: function(err) {
							console.error('Call Failed: ', err);
						}
					});
				});
			}
		}
	}
</script>

<style lang="scss">
	/deep/.u-drawer-bottom {
		background-color: #f7f7f7;
	}

	.price {
		font-size: 40rpx !important;
		font-weight: 550;
		color: #EF5205;

		text {
			font-weight: 500;
			font-size: 20rpx;
		}
	}

	.out {
		padding: 20rpx;

		.card {
			margin-bottom: 20rpx;
			padding: 30rpx;
			background: #FFFFFF;
			border-radius: 10rpx;

			.top {
				padding-bottom: 24rpx;
				border-bottom: 1rpx solid #DFDFDF;
				font-size: 28rpx;
				font-weight: bold;

				text {
					font-size: 20rpx;
					font-weight: 400;
					color: #333333;
				}
			}

			.address {
				image {
					width: 43rpx;
					height: auto;
					margin-right: 30rpx;
					flex-shrink: 0;
				}

				.message {
					.name {
						font-size: 32rpx;
						font-weight: bold;

						text {
							font-size: 28rpx;
							font-weight: 500;
						}
					}

					text {
						font-size: 24rpx;
					}

					.number {
						font-size: 28rpx;
						font-weight: bold;
						color: #222222;
					}
				}
			}

			.right-icon {
				margin-left: 40rpx;
				width: 17rpx;
				height: auto;
				flex-shrink: 0;
			}

			.card-item {
				padding-top: 30rpx;

				&:not(:last-child) {
					padding-bottom: 30rpx;
					border-bottom: 1rpx solid #DFDFDF;
				}
			}

			.item-message {
				font-size: 24rpx;
				margin: 20rpx 0;

				text {
					color: #999;
				}

				image {
					margin-top: -5rpx;
					margin-left: 15rpx;
					width: 12rpx;
				}
			}

			.shop-message {
				font-size: 32rpx;
				font-weight: 550;

				image {
					width: 28rpx;
					height: auto;
					margin-right: 10rpx;
				}

				.standing {
					margin-left: 18rpx;
					width: 64rpx;
					height: 32rpx;
					background: #F43000;
					border-radius: 4rpx;
					font-size: 24rpx;
					color: #FFFFFF;
				}

				.standing2 {
					background: #606DCE;
				}
			}

			.right-icon {
				width: 12rpx;
				height: auto;
			}

			.goods-img {
				width: 180rpx;
				height: 180rpx;
				border-radius: 10rpx;
				flex-shrink: 0;
			}

			.message {
				margin-left: 36rpx;

				.cate {
					width: fit-content;
					width: -webkit-fit-content;
					width: -moz-fit-content;
					padding: 3rpx;
					background: #fafafa;
					font-size: 22rpx;
					border-radius: 5rpx;
				}

				view {
					font-size: 28rpx;
				}
			}
		}
	}

	.placeholder {
		width: 100%;
		height: 174rpx;
	}

	.btn-box {
		position: fixed;
		bottom: 0;
		padding: 18rpx 34rpx 0 41rpx;
		width: 100%;
		height: 144rpx;
		background: #FFFFFF;
		box-shadow: 0rpx 1rpx 0rpx 0rpx #E7E7E7;
		border-radius: 10rpx;

		.total {
			font-size: 24rpx;
			color: #222;
		}

		.btn {
			width: 210rpx;
			height: 79rpx;
			background: linear-gradient(to right, #5F6ACC, #6E99DE);
			border-radius: 45rpx;
			font-size: 32rpx;
			color: #FFFFFF;
		}
	}

	.coupon {
		height: 100%;
		padding: 0 30rpx;
		background-color: #f6f6f6;

		.cou_tit {
			padding: 30rpx 0;
			text-align: center;
			font-weight: bold;
			background: #f6f6f6;
			position: fixed;
			top: 0;
			width: 100%;
			z-index: 3;
		}

		.cou_item {
			margin-bottom: 40rpx;
			position: relative;
			width: 100%;
			height: 210rpx;
			overflow: hidden;
			border-radius: 30rpx;

			.cou_grey {
				position: absolute;
				top: 0;
				bottom: 0;
				left: 0;
				right: 0;
				z-index: 2;
				background: rgba(76, 76, 76, 0.5);
			}

			.left {
				width: 471rpx;
				height: 210rpx;
				background: #fff;
				padding: 27rpx 40rpx 0rpx 30rpx;

				.code {
					font-size: 22rpx;
					color: #666666;
				}

				.cou_price {
					margin-right: 25rpx;
					color: #E55D23;
					font-size: 88rpx;
					font-weight: 550;

					text {
						margin-top: 32rpx;
						font-size: 26rpx;
						margin-right: 10rpx;
					}
				}

				.title {
					font-size: 26rpx;
					font-weight: bold;
					color: #333333;
				}

				.tips {
					margin-top: 10rpx;
					width: 154rpx;
					height: 31rpx;
					background: #E55D23;
					font-size: 20rpx;
					color: #FFFFFF;
				}

				.time {
					height: 20rpx;
					font-size: 22rpx;
					color: #666666;
					margin-top: 35rpx;
				}
			}

			.status {
				width: 220rpx;
				height: 210rpx;
				position: absolute;
				right: 0;
				top: 50%;
				transform: translateY(-50%);
				font-size: 30rpx;
				font-weight: bold;
				color: #fff;
				background: #606DCE;
			}
		}
	}
</style>